﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace PaiKe.Core.FileDataBase
{
    /// <summary>
    /// 包文件管理器
    /// </summary>
    public class PackFileManager
    {

        private PackFile _pf;
        private List<string> _pathList = new List<string>();


        public void AddSourceFile(string source)
        {
            if (File.Exists(source))
                this._pathList.Add(source);
            else
                throw new FileNotFoundException(source);
        }

        public void LoadPackFile(string path)
        {
            if (!File.Exists(path))
            {
                throw new FileNotFoundException(path);
            }
            if (_pf != null)
            {
                _pf.Close();
                _pf = null;
            }
            FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
            BinaryReader br = new BinaryReader(fs);
            if (br.ReadString() != "PackFile")
            {
                throw new InvalidCoalescentFileException("该文件不是有效的包文件");
            }
            this._pf = new PackFile(fs,br);
        }


        /// <summary>
        /// 生成并合文件
        /// </summary>
        /// <param name="path"></param>
        /// <param name="useDeflate"></param>
        public void Build(string path)
        {
            using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write))
            {
                BinaryWriter bw = new BinaryWriter(fs);
                bw.Write("PackFile");
                bw.Write(this._pathList.Count);
                foreach (string f in this._pathList)
                {
                    FileInfo fi = new FileInfo(f);
                    bw.Write(fi.Length);
                    fi = null;
                }
                foreach (string f in this._pathList)
                {
                    bw.Write(Path.GetFileName(f));
                }
                foreach (string f in this._pathList)
                {
                    bw.Write(File.ReadAllBytes(f));
                    bw.Flush();
                }
            }
        }

        // Properties
        public PackFile CurrentPackFile
        {
            get
            {
                return this._pf;
            }
        }
    }
}
